import { Injectable } from '@nestjs/common'
import { CreateCrudDto } from './dto/create-crud.dto'
import { UpdateCrudDto } from './dto/update-crud.dto'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository, Like } from 'typeorm'
import { Crud } from './entities/crud.entity'
import { Tags } from './entities/tags.entity'
@Injectable()
export class CrudService {
  constructor(
    @InjectRepository(Crud) private readonly crud: Repository<Crud>,
    @InjectRepository(Tags) private readonly tags: Repository<Tags>
  ) {}

  //
  /* 通过前端传入的userId 查到当前id 的crud信息，然后拿到前端传入的tags [tag1,tag2,tag3]
进行遍历 给tag实例进行赋值 然后调用保存方法添加tag 添加完之后 通过 tagList 保存该tag类
最后把tagList 赋给 crud类的tags属性 然后重新调用save 进行更新
 */
  async addTags(params: { tags: string[]; userId: string }) {
    console.log(params)
    const crudInfo = await this.crud.findOne({ where: { id: params.userId } })
    const tagList: Tags[] = []
    for (let i = 0; i < params.tags.length; i++) {
      let T = new Tags()
      T.tags = params.tags[i]
      await this.tags.save(T)
      tagList.push(T)
    }
    crudInfo.tags = tagList
    console.log(crudInfo)
    return this.crud.save(crudInfo)
  }

  create(createCrudDto: CreateCrudDto) {
    const data = new Crud()
    data.name = createCrudDto.name
    data.desc = createCrudDto.desc
    return this.crud.save(data)
  }

  async findAll(query: { keyword: string; page: number; pageSize: number }) {
    const data = await this.crud.find({
      relations: ['tags'], //多表联查需要加relations  会自动将已有的关系一并查出来
      where: {
        name: Like(`%${query.keyword}%`),
      },
      order: {
        create_time: 'DESC', //倒序
        id: 'ASC', //正序
      },
      skip: (query.page - 1) * query.pageSize, //偏移量   相当于数据库里的limit
      take: query.pageSize,
    })
    const total = await this.crud.count({
      where: {
        name: Like(`%${query.keyword}%`),
      },
    })
    return { data, total }
  }

  findOne(id: string) {
    return `This action returns a #${id} crud`
  }

  update(id: string, updateCrudDto: UpdateCrudDto) {
    return this.crud.update(id, updateCrudDto)
  }

  remove(id: string) {
    return this.crud.delete(id)
  }
}
